package cn.git.demo.controller.order;

import cn.git.demo.pojo.SysUser;
import cn.git.demo.service.SysUserService;
import cn.git.demo.utils.MD5Utils;
import com.sun.xml.internal.stream.writers.WriterUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @RequestMapping(value = "/user/toLogin.do")
    public String toLogin( ){

        return "login";
    }
    @RequestMapping(value = "/user/login.do")
    public @ResponseBody String login(String username, String password, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        Integer flag = null;
        SysUser user = sysUserService.selectSysUserByCode(username);
        if(username.equals(user.getName()) && MD5Utils.md5(password).equals(user.getPassword())){
            request.getSession().setAttribute("user",user);
            flag = 1;
        }else {
            flag = 0;
        }
       /*
       写给回调函数的数据，两种写入方式：1，调用write强制写入2，利用@RequestBody注解，将返回数据对象直接return回去。
       response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(flag);
        writer.flush();
        writer.close();*/
        return flag.toString();
    }
    @RequestMapping(value = "/user/toRegister.do")
    public String toRegister(){
        return "register";
    }
    /*
    * 问题：前端用json格式传入的值，不是一个SysUser对象，在存入对象的时候需要创建一个新的SysUser对象进行赋值
    * 这样太麻烦，有没有办法从前端直接传入SysUser对象。
    * */
    @RequestMapping(value = "/user/register.do")
    public @ResponseBody String register(String username,String password,String email){
        Integer flag =null;
        SysUser user = sysUserService.selectSysUserByCode(username);
        if(user!=null){
            flag = 0;
        }else{
            SysUser sysUser = sysUserService.selectSysUserByEmail(email);
            if (sysUser!=null){
                flag = 1;
            }else {
                SysUser sysUser1 = new SysUser();
                sysUser1.setName(username);
                sysUser1.setPassword(password);
                sysUser1.setEmail(email);
                sysUserService.addSysUser(sysUser1);
                flag = 2;
            }
        }
        return flag.toString();
    }

    @RequestMapping(value = "/user/signOut")
    public String signOut(HttpSession session){


        session.removeAttribute("user");

        return "login";
    }


}
